#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "huffman.h"

#define putbit(b) putchar((b) ? '1' : '0')

int getbit() {
  int ret;
  ret = getchar ();
  if (ret == EOF) return EOF;
  return ret == '0' ? 0 : 1;
}

void myputchar (int c) {
  int i;
  for (i = 7; i >= 0; i--) putbit ((c >> i) & 1);
}

int mygetchar () {
  int i, ret = 0;
  for (i = 7; i >= 0; i--) {
    ret += getbit () * pow (2, i);
  }
  return ret;
}

int main (int argc, char *argv[]) {
  int b, c;
  FILE *f;
  huff_node curr;
  
  if (argc == 2) {
    if (!(f = fopen (argv[1], "r"))) {
      printf ("An error occured while opening %s\n", argv[1]);
      exit (EXIT_FAILURE);
    }
  } else f = stdin;

  c = mygetchar ();
  putchar (c);
  huff_tree_init (c);
  curr = thetree.root;
  
  while ((b = getbit()) != EOF) {
    if (b == 0 && huff_node_isspecial (curr)) {
      //printf ("diese found\n");
      c = mygetchar ();
      putchar (c);
      huff_tree_modify (c);
      curr = thetree.root;
      continue;
    }
    curr = b ? curr->right : curr->left;
    if (huff_node_isleaf (curr)) {
      //printf ("character found\n");
      putchar (curr->c);
      huff_tree_modify (curr->c);
      curr = thetree.root;
    }
  }

  return (EXIT_SUCCESS);
}
